package com.xuan.commons.config.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;

import java.util.Calendar;

/**
 * @author renzhengxuan
 * @date 2021/5/23
 */
public class JwtConfig {
    /**
     * 获取token
     * @param username
     * @param secret
     * @return
     */
    public static String getToken(String username,String secret){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,300);//5分钟
        String token = JWT.create().withClaim("username", username)
                .withExpiresAt(calendar.getTime())//token过期时间为5分钟
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 验证token
     * @return
     */
    public static String getUsername(String token){
        try {
            String username = JWT.decode(token).getClaim("username").asString();
            return username;
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }
}
